<?php

namespace app\home\controller\device;

use app\home\controller\AuthController;
use Endroid\QrCode\QrCode;
use services\{MiniProgramService, UtilService as Util, JsonService as Json};
use app\home\model\store\{StoreDevice, DeviceCategory};
use app\home\model\system\SystemStore;
use services\FormBuilder as Form;
use think\facade\Db;
use think\facade\Route as Url;

/**
 * Class Device
 * @package app\home\controller\device
 */
class Device extends AuthController
{
    /**
     * 设备的首页
     */
    public function index()
    {
        $where = Util::getMore([
            ["status", ""],
            ["store_id", ''],
            ["device_name", ""]
        ], $this->request);
        // 获取所有的分类
        $this->assign('where', $where);
        $this->assign("store_list", SystemStore::where("wxapp_id", $this->wxapp_id)->where("is_del", 0)->field("id, name")->order("id DESC")->select());
        $this->assign("device_category", DeviceCategory::getList());
        // 获取所有的设备
        $this->assign(StoreDevice::systemPage($where));
        return $this->fetch();
    }

    /**
     * 新增的页面
     * @return string
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public function create()
    {
        $f = array();
        $f[] = Form::input("device_name", "设备名称")->placeholder("请输入设备名称");
        $f[] = Form::input("device_no", "设备编号")->placeholder("请输入设备编号");
        $f[] = Form::input("pwd", "设备密码")->placeholder("请输入设备密码");
        $f[] = Form::input("address", "设备地址")->placeholder("请输入设备地址");
        $f[] = Form::select("store_id", "选择门店")->setOptions(function () {
            $list = SystemStore::dropList();
            $menus = [];
            foreach ($list as $menu) {
                $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
            }
            return $menus;
        })->filterable(1);
        $f[] = Form::select("category_id", "选择分类")->setOptions(function () {
            $list = DeviceCategory::getList();
            $menus = [];
            foreach ($list as $menu) {
                $menus[] = ["value" => $menu["id"], "label" => $menu["cat_name"]];
            }
            return $menus;
        });
        $f[] = Form::radio("status", "状态", 10)->options([["label" => "正常", "value" => 10], ["label" => "失联", "value" => 20], ["label" => "维护", "value" => 30]]);
        $form = Form::make_post_form("添加设备", $f, Url::buildUrl("save"));
        $this->assign(compact('form'));
        return $this->fetch("public/form-builder");
    }

    /**
     * @param int $id
     */
    public function save($id = 0)
    {
        $data = Util::getMore([
            ["device_name", ""],
            ["device_no", ""],
            ["address", ""],
            ["store_id", 0],
            ["category_id", 0],
            ["status", 0],
        ]);
        if (!$id) {
            if (StoreDevice::where("id", $id)->count()) return Json::fail("添加的设备已经存在");
        }
        if ($data["store_id"] == 0) return Json::fail("请选择门店");
        if ($data["status"] == 0) return Json::fail("请选择设备的状态");
        $data["wxapp_id"] = $this->wxapp_id;
        if ($id) {
            $res = StoreDevice::edit($data, $id);
            if ($res) {
                return Json::successful("编辑成功");
            } else {
                return Json::fail("编辑失败");
            }
        } else {
            $data["add_time"] = time();
            $res = StoreDevice::create($data);
            if ($res) {
                return $this->successful("新增成功");
            } else {
                return $this->failed("添加设备失败，请稍后再试");
            }
        }

    }


    /**
     * 编辑的页面
     * @param $id
     * @return false|string
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public function edit($id)
    {
        $service = StoreDevice::get($id);
        if (!$service) return Json::fail("数据不存在");

        $f = [
            Form::input("device_name", "设备名称", $service["device_name"])->placeholder("请输入设备名称"),
            Form::input("device_no", "设备编号", $service["device_no"])->placeholder("请输入设备编号"),
            Form::input("pwd", "设备密码")->placeholder("请输入设备密码"),
            Form::input("address", "设备地址", $service["address"])->placeholder("请输入设备地址"),
            Form::select("store_id", "选择门店", (string)$service->getData('store_id'))->setOptions(function () {
                $list = SystemStore::dropList();
                $menus = [];
                foreach ($list as $menu) {
                    $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
                }
                return $menus;
            })->filterable(1),
            Form::select("category_id", "选择分类", (string)$service->getData('category_id'))->setOptions(function () {
                $list = DeviceCategory::getList();
                $menus = [];
                foreach ($list as $menu) {
                    $menus[] = ["value" => $menu["id"], "label" => $menu["cat_name"]];
                }
                return $menus;
            }),
            $f[] = Form::radio("status", "状态", $service["status"])->options([["label" => "正常", "value" => 10], ["label" => "失联", "value" => 20], ["label" => "维护", "value" => 30]]),
        ];
        $form = Form::make_post_form("修改数据", $f, Url::buildUrl("save", compact('id')));
        $this->assign(compact('form'));
        return $this->fetch("public/form-builder");
    }

    /**
     * 维护商品
     * @param int $id
     * @return false|string
     */
    public function repair($id = 0)
    {
        if ($id == 0) return Json::fail("修改的设备不存在");
        $res = StoreDevice::edit(["status" => 30], $id);
        if ($res) {
            return Json::successful("维护成功");
        }
        return Json::fail("维护失败,请稍后再试");
    }

    /**
     * 删除
     * @param int $id
     * @return false|string
     */
    public function delete($id = 0)
    {
        if ($id == 0) return Json::fail("参数错误");
        if (!StoreDevice::be(["id" => $id])) return Json::fail("数据不存在");
        if (StoreDevice::edit(["is_del" => 1], $id))
            return Json::successful("删除成功");
        else
            return Json::fail("删除失败");
    }

    /**
     * TODO 生成二维码
     * @param $id
     * @return false|string
     */
    public function restart($id = 0)
    {
        if (!$id) return Json::fail("请传入ID");
        // 新建目录
        $devicePath = $_SERVER["DOCUMENT_ROOT"] . DS . "uploads" . DS . "device" . DS . $this->wxapp_id;
        if (!is_dir($devicePath)) {
            @mkdir($devicePath, 0777, true);
        }
        $storeDeviceData = StoreDevice::get(["id" => $id]);
        $store_id = $storeDeviceData["store_id"];
        // $response = MiniProgramService::qrcodeService()->getQrCode("pages/car_wash_one/index?id={$id}&store_id={$store_id}");
        $data_arr = ['id' => $id, 'store_id' => $store_id];
        $response = MiniProgramService::appCodeUnlimitService(http_build_query($data_arr, true), [
            'page' => 'pages/car_wash_one/index',
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save($devicePath, "{$id}.png");
        }
        if (!isset($filename)) {
            return Json::fail("生成二维码失败,请稍后再试");
        }
        $url = "http://" . $_SERVER["HTTP_HOST"] . "/uploads/device" . DS . $this->wxapp_id . DS . $filename;
        $res = StoreDevice::edit(["url_code" => $url], $id);
        if ($res)
            return Json::successful("生成二维码成功");
        else
            return Json::fail("生成二维码失败");
    }

    public function debug($id)
    {
        $vo = Db::name("store_device")->where("id", $id)->find();
        $this->assign(compact("vo"));
        return $this->fetch();
    }

    public function getData($id)
    {
        $data = Db::name("store_device")->where("id", $id)->find();
        return Json::successful(compact("data"));

    }
}